package com.zhx.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import com.zhx.database.DbUtil;
import com.zhx.menu.Menu;
import com.zhx.menu.RoleMenu;
import com.zhx.role.Role;

public class RoleMenuDao extends BaseDao{

	@Override
	protected RoleMenu handle(ResultSet rs) throws SQLException {
		try{
			RoleMenu roleMenu = new RoleMenu();
			roleMenu.setId(rs.getInt("id"));
			roleMenu.setRoleId(rs.getString("role_id"));
			roleMenu.setMenuId(rs.getString("menu_id"));
			roleMenu.setCreateTime(rs.getTimestamp("create_time"));
			roleMenu.setUpdateTime(rs.getTimestamp("update_time"));
			return roleMenu;
		}catch(SQLException e){
			throw new SQLException("结果集转为实例失败!",e);
		}
	}
	
    public List<RoleMenu> getRoleMenusByRoleId(String roleId) throws SQLException{
    	List<RoleMenu> roleMenus = new ArrayList<RoleMenu>();
    	if(roleId != null) {
    		DbUtil dbUtil = new DbUtil();
			
			String sql = "select * from sys_role_menu where role_id = '"+ roleId +"'";
			ResultSet rs = dbUtil.executeQuery(sql);
			while (rs.next()) {
				RoleMenu roleMenu = new RoleMenu();
				roleMenu = handle(rs);
				roleMenus.add(roleMenu);
			}
    	}
    	return roleMenus;
    }
    
    public List<Menu> getMenusByRoleId(String roleId) throws SQLException{
    	List<Menu> menus = new ArrayList<Menu>();
    	if(roleId != null) {
    		DbUtil dbUtil = new DbUtil();
			
			String sql = "select * from sys_role_menu where role_id = '"+ roleId +"'";
			ResultSet rs = dbUtil.executeQuery(sql);
			while (rs.next()) {
				RoleMenu roleMenu = new RoleMenu();
				roleMenu = handle(rs);
				
				Menu menu = new Menu();
				MenuDao menuDao = new MenuDao();
				menu = menuDao.getMenuByMenuId(roleMenu.getMenuId());
				
				menus.add(menu);
			}
    	}
    	return menus;
    }
	
	/**
	 * 
	 * @param roleId
	 * @param menus
	 * @throws SQLException
	 */
	public void addRoleMenus(String roleId,String[] menus) throws SQLException {
		if(roleId != null && menus.length != 0) {
			DbUtil dbUtil = new DbUtil();
			PreparedStatement pstmt = null;
			Connection conn = dbUtil.getConn();
			try {
				for (String menuId : menus) {
					StringBuffer sqlBuff = new StringBuffer(
							"insert into sys_role_menu(menu_id, role_id, create_time, update_time)");
					sqlBuff.append("values(?,?,?,?)");
					
						pstmt = conn.prepareStatement(sqlBuff.toString());
						pstmt.setString(1, menuId);
						pstmt.setString(2, roleId);
						pstmt.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
						pstmt.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
						pstmt.executeUpdate();
					
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				dbUtil.close(pstmt);
			}
		}
	}

}
